<template>
	<div class="my-detail">
		<van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
			<van-swipe-item v-for="(item, i) in product.picList" :key="i">
				<van-image :src="APIDomainName + item.md" class="product-image" />
			</van-swipe-item>
		</van-swipe>
		<div class="product-info">
			<van-cell title="商品编号" :value="product.id" class="product-cell" />
			<van-cell title="商品名称" :value="product.name" class="product-cell" />
			<van-cell title="商品标题" :value="product.title" class="product-cell" />
			<van-cell title="商品规格" :value="product.spec" class="product-cell" />
			<van-cell title="硬盘" :value="product.disk" class="product-cell" />
			<van-cell title="CPU" :value="product.cpu" class="product-cell" />
			<van-cell title="内存" :value="product.memory" class="product-cell" />
			<van-cell title="显卡" :value="product.video_card" class="product-cell" />
			<van-cell title="分辨率" :value="product.resolution" class="product-cell" />
			<van-cell title="上架时间" :value="product.shelf_time" class="product-cell" />
			<van-cell title="单价" :value="product.price" class="product-cell" />
		</div>
		<!-- 商品购买区域 -->
		<van-cell class="buy-section">
			<template #default>
				<div class="count-buy">
					<div>购买数量</div>
					<van-stepper v-model="count" integer min="1" class="quantity-stepper" />
					<van-button type="primary" size="small" @click="onClickAddShopcart" :loading="isAddingToCart"
						class="add-to-cart-button">
						{{ isAddingToCart? '正在加入...' : '加入购物车' }}
					</van-button>
				</div>
				<div class="count-like">
					<van-button :type="isFavorite? 'secondary' : 'primary'" size="small" @click="toggleFavorite"
						:loading="isAddingToLike" class="favorite-button">
						{{ isFavorite? '取消收藏' : '加入收藏' }}
					</van-button>
				</div>
			</template>
		</van-cell>
		<van-button type="primary" size="large" @click="$router.back()" class="back-button">返回</van-button>
	</div>
</template>

<script>
	import {
		showToast
	} from 'vant';
	import {
		getProductDetailByIdAPI
	} from "@/api/product.js";
	import {
		addCartAPI
	} from "@/api/cart.js";

	export default {
		data() {
			return {
				product: {},
				count: 1,
				isLoadingProduct: true,
				productId: null,
				isAddingToCart: false,
				isAddingToLike: false,
				isFavorite: false // 新增：表示当前商品是否已被收藏
			};
		},
		created() {
			this.productId = this.$route.params.id;
			if (this.productId) {
				this.fetchProductDetail();
			} else {
				console.error('未获取到商品编号');
				showToast('未获取到商品编号，请重新选择商品');
			}
		},
		methods: {
			showProductDetail(id) {
				this.productId = id;
				this.fetchProductDetail();
			},
			fetchProductDetail() {
				if (!this.productId) {
					console.error('未接收到有效的商品编号');
					showToast('未获取到商品编号，请重新选择商品');
					return;
				}
				this.isLoadingProduct = true;
				getProductDetailByIdAPI(this.productId)
					.then(result => {
						if (result.data && result.data.id) {
							this.product = result.data;
							const date = new Date();
							const year = date.getFullYear();
							const month = String(date.getMonth() + 1).padStart(2, '0');
							const day = String(date.getDate()).padStart(2, '0');
							this.product.shelf_time = `${year}-${month}-${day}`;
							// 检查商品是否已被收藏
							const favorites = JSON.parse(localStorage.getItem('favorites')) || [];
							this.isFavorite = favorites.some(favorite => favorite.productData.id === this.product.id);
						} else {
							console.error('获取的商品详情中商品编号为空');
							showToast('获取商品信息失败，请稍后重试');
						}
						this.isLoadingProduct = false;
					})
					.catch(error => {
						console.error('获取商品详情失败:', error);
						showToast('获取商品详情失败，请稍后再试');
						this.isLoadingProduct = false;
					});
			},
			onClickAddShopcart() {
				if (this.isLoadingProduct) {
					showToast('商品信息正在加载，请稍后再试');
					return;
				}
				if (!this.product.id) {
					showToast('商品编号不能为空，请稍后重试');
					return;
				}
				if (this.count <= 0) {
					showToast('购买数量必须大于 0，请输入正确的数量');
					return;
				}
				this.isAddingToCart = true;
				const params = {
					product_id: this.product.id,
					count: this.count
				};
				addCartAPI(params)
					.then(result => {
						this.isAddingToCart = false;
						if (result.success) {
							showToast(result.msg || '商品已成功添加到购物车');
						} else {
							showToast(result.msg || '添加购物车失败，请稍后重试');
						}
					})
					.catch(error => {
						this.isAddingToCart = false;
						console.error('添加购物车失败:', error);
						showToast('添加购物车失败，请稍后重试');
					});
			},
			toggleFavorite() {
				if (this.isLoadingProduct) {
					showToast('商品信息正在加载，请稍后再试');
					return;
				}
				if (!this.product.id) {
					showToast('商品编号不能为空，请稍后重试');
					return;
				}
				this.isAddingToLike = true;
				const favorites = JSON.parse(localStorage.getItem('favorites')) || [];
				if (this.isFavorite) {
					// 取消收藏
					const index = favorites.findIndex(favorite => favorite.productData.id === this.product.id);
					if (index > -1) {
						favorites.splice(index, 1);
					}
					showToast('已取消收藏');
				} else {
					// 收藏
					const newFavorite = {
						id: Date.now(),
						title: this.product.title,
						type: "product",
						productData: this.product
					};
					favorites.push(newFavorite);
					showToast('已成功添加到收藏');
				}
				localStorage.setItem('favorites', JSON.stringify(favorites));
				this.isFavorite = !this.isFavorite;
				this.isAddingToLike = false;
			}
		}
	};
</script>

<style scoped>
	.my-detail {
		background-color: #fff;
		padding: 15px;
		border-radius: 10px;
		box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
	}

	.my-swipe {
		margin-bottom: 15px;
	}

	.product-image {
		width: 100%;
		height: 300px;
		object-fit: cover;
		border-radius: 10px;
	}

	.product-info {
		margin-bottom: 15px;
	}

	.product-cell {
		border-bottom: 1px solid #e0e0e0;
		padding: 10px 0;
	}

	.buy-section {
		margin-bottom: 15px;
	}

	.count-buy {
		display: flex;
		flex-direction: row;
		margin: 10px 0px;
		justify-content: space-between;
		align-items: center;
	}

	.quantity-stepper {
		width: 100px;
	}

	.add-to-cart-button {
		width: 120px;
	}

	.favorite-button {
		width: 120px;
	}

	.back-button {
		width: 100%;
		margin-top: 15px;
	}
</style>